import requests
import json
from django.http import JsonResponse, HttpResponseNotAllowed, HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt

import datetime
import sxtwl
from chinese_calendar import is_holiday, is_workday

@csrf_exempt
def get_weather(request):
    city = '101190101'#南京
    url = 'http://t.weather.sojson.com/api/weather/city/'+city
    response = requests.get(url)
    allWeatherInfo = response.json()
    # 城市
    cityInfo = allWeatherInfo['cityInfo']['city']
    # 天气
    weatherInfo = allWeatherInfo['data']['forecast'][0]
    # 温度
    str_tem_low = weatherInfo['low'].split(' ')
    str_tem_high = weatherInfo['high'].split(' ')
    tempInfo = f"{str_tem_low[1]}~{str_tem_high[1]}"

    weather_data = {
            "city": cityInfo,
            "weather": weatherInfo['type'],
            "temperature": tempInfo
        }
    return JsonResponse(weather_data)

@csrf_exempt
def get_days(request):
    today = datetime.date.today()
    days = {}
    # 今日日期与星期数
    week = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
    weekday = today.isoweekday()  # 获取周几
    lunarday = lunarDay(today)
    days["today"] = f"{today.year}年{today.month}月{today.day}日{week[weekday-1]}, {lunarday}"

    years,months,ddays,delta_days = loveDays(today)
    lovedaytext = ""
    if ddays == 0:
        if months == 0:
            lovedaytext =  f"{years}年"
        else:
            lovedaytext =  f"{years}年{months}月"
    else:
        if months == 0:
            lovedaytext =  f"{years}年零{ddays}天"
        else:
            lovedaytext =  f"{years}年{months}月{ddays}天"
    days["loveddays"] = f"{delta_days}天"
    days["lovedays"] = lovedaytext
    
    ywBirthday = toBrithday(today)
    birthdayText = ""
    if ywBirthday == 0:
        birthdayText = "阅宝宝生日快乐！"
    else:
        birthdayText = f"阅宝宝生日还有{ywBirthday}天"
    days["ywbirthday"] = birthdayText
    
    Holiday = toHoliday(today)
    if Holiday == 0:
        HolidayText = "今天是休息日，好好放松一下！"
    else:
        HolidayText = f"休息日还有{Holiday}天"
    days["holiday"] = HolidayText
    
    bfMoneyDay = moneyDays(today,5)
    ywMoneyDay = moneyDays(today,15)
    if bfMoneyDay == 0:
        MoneyText = "今天帆小生发工资啦！"
    elif ywMoneyDay == 0:
        MoneyText = "今天阅宝宝发工资啦！"
    else:
        MoneyText = f"发工资倒计时: 帆小生{bfMoneyDay}天, 阅宝宝{ywMoneyDay}天"
    days["moneyday"] = MoneyText
    return JsonResponse(days)
    
# 计算在一起的时长
def loveDays(today):
    # 获得天数
    loveday = datetime.date(2019, 5, 30)
    delta_days = (today - loveday).days
    # 获得年月
    months = (today.year - loveday.year)*12 + (today.month - loveday.month)
    years = months//12
    months = months%12
    # 获得日，暂未使用
    next_month_oneday = today.replace(day=28) + datetime.timedelta(days=4)  # 获取到下个月的某天
    next_month_oneday_days = datetime.timedelta(days=next_month_oneday.day)  # 获取该天在该月的天数
    this_month_final = next_month_oneday - next_month_oneday_days  # next_month_oneday减去自身的天数，即可得到本月的月底最后一天
    if this_month_final.day <= 30:
        days = today.day - this_month_final.day
    else:
        days = today.day - 30
    if days<0:
        months = months - 1
        days = today.day
        last_month_final = today - datetime.timedelta(days=today.day)
        if last_month_final.day == 31:
            days = days+1
    return [years,months,days,delta_days]

# 计算发工资天数（每个月到某日的天数，除去节假日）
def moneyDays(today,moneyday):
    # 先通过当月计算
    tempday = datetime.date(today.year, today.month, moneyday)
    try:
        while is_holiday(tempday):
            tempday = tempday - datetime.timedelta(days=1)
    except NotImplementedError:
        # 处理异常的代码
        print("OverDate! use 'pip install --upgrade chinese_calendar' to latest data")
    to_money_day = (tempday-today).days

    # 时间小于0，则跳转到下个月，甚至下下个月
    # 如【20230929】，在【202310】并不发工资，需要到【202311】
    tempmonth = today.month
    print(to_money_day)
    while to_money_day < 0:
        tempyear = today.year
        tempmonth = tempmonth+1 
        if tempmonth>12:
            tempmonth = 1
            tempyear = tempyear+1
        tempday = datetime.date(tempyear, tempmonth, moneyday)
        try:
            while is_holiday(tempday):
                tempday = tempday - datetime.timedelta(days=1)
        except NotImplementedError:
            # 处理异常的代码
            print("OverDate! use 'pip install --upgrade chinese_calendar' to latest data")
        to_money_day = (tempday-today).days
    return to_money_day

# 计算农历生日
def toBrithday(today):
    #生日期限
    yw_birthday_lunar = sxtwl.fromLunar(today.year, 4, 11)
    yw_birthday_solar = datetime.date(yw_birthday_lunar.getSolarYear(), 
                                    yw_birthday_lunar.getSolarMonth(),
                                    yw_birthday_lunar.getSolarDay())
    to_yw_birthday = (yw_birthday_solar-today).days
    if to_yw_birthday < 0:
        yw_birthday_lunar = sxtwl.fromLunar(today.year+1, 4, 11)
        yw_birthday_solar = datetime.date(yw_birthday_lunar.getSolarYear(), 
                                        yw_birthday_lunar.getSolarMonth(),
                                        yw_birthday_lunar.getSolarDay())
        to_yw_birthday = (yw_birthday_solar-today).days
    return to_yw_birthday

# 计算休息日（除去节假日）
def toHoliday(today):
    to_holiday = 0
    tempday = today
    try:
        while is_workday(tempday):
            to_holiday = to_holiday+1
            tempday = tempday + datetime.timedelta(days=1)
    except NotImplementedError:
        # 处理异常的代码
        print("OverDate! use 'pip install --upgrade chinese_calendar' to latest data")
    return to_holiday

# 计算农历
def lunarDay(today):
    #今日农历
    ymc = [u"正", u"二", u"三", u"四", u"五", u"六", u"七", u"八", u"九", u"十", u"十一", u"十二",]
    rmc = [u"初一", u"初二", u"初三", u"初四", u"初五", u"初六", u"初七", u"初八", u"初九", u"初十",
        u"十一", u"十二", u"十三", u"十四", u"十五", u"十六", u"十七", u"十八", u"十九",
        u"二十", u"廿一", u"廿二", u"廿三", u"廿四", u"廿五", u"廿六", u"廿七", u"廿八", 
        u"廿九", u"三十", u"卅一"]
    Gan = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"]
    Zhi = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"]
    day = sxtwl.fromSolar(today.year, today.month, today.day)
    if sxtwl.getRunMonth(today.year) == day.getLunarMonth():
        a = "润" + ymc[day.getLunarMonth()-1] + "月" + rmc[day.getLunarDay()] #+ "日"
    else:
        a = ymc[day.getLunarMonth()-1] + "月" + rmc[day.getLunarDay()-1] #+ "日"
    yTG = day.getYearGZ()
    mTG = day.getMonthGZ()
    dTG = day.getDayGZ()
    c = Gan[yTG.tg] + Zhi[yTG.dz] + "年" + Gan[mTG.tg] + Zhi[mTG.dz] + "月" + Gan[
        dTG.tg] + Zhi[dTG.dz] #+ "日"
    return '农历' + a

# 计算到目标日的时长
def calDays(today,targetDay):
    # 获得天数
    tmp = targetDay.split("-")
    Tday = datetime.date(int(tmp[0]), int(tmp[1]), int(tmp[2]))
    return (today - Tday).days
